package cn.sdstudio.service.impl;

import cn.sdstudio.config.BaiduMapConfig;
import cn.sdstudio.enums.BaseTravel;
import cn.sdstudio.service.MapRouterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * @author Zyq
 * @version 1.0
 * @date 2025/4/29 周二
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class MapRouterServiceImpl implements MapRouterService {

    private final WebClient webClient;
    private final BaiduMapConfig baiduMapConfig;

    /**
     * 地址字符串转经纬度（百度地图地理编码）
     */
    @Override
    public String addressToLatLng(String address) {
        log.info("开始查询地址: {}", address);

        String responseBody = webClient.get()
                .uri(baiduMapConfig.getGeocodingUrl(),uriBuilder -> uriBuilder
                        .queryParam("address", address)
                        .queryParam("output", "json")
                        .queryParam("ak", baiduMapConfig.getAk())
                        .build())
                .retrieve()
                .bodyToMono(String.class)
                .block(); // 这里使用 `block()` 让它同步执行

        log.info("百度地图API返回: {}", responseBody);

        JSONObject jsonObject = new JSONObject(responseBody);
        int status = jsonObject.getInt("status");

        if (status == 0) {
            JSONObject result = jsonObject.getJSONObject("result");
            JSONObject location = result.getJSONObject("location");
            double lat = location.getDouble("lat");
            double lng = location.getDouble("lng");

            log.info("获取到经纬度: lat={}, lng={}", lat, lng);
            return lat + "," + lng;
        } else {
            throw new RuntimeException("地理编码失败: " + jsonObject.optString("msg", "未知错误"));
        }
    }

    /**
     * 获取路线信息（同步方式）
     */
    @Override
    public JSONObject getRouteFromAddress(String originAddress, String destinationAddress, BaseTravel mode) {
        String origin = addressToLatLng(originAddress);
        log.info("起点坐标: {}", origin);

        String destination = addressToLatLng(destinationAddress);
        log.info("终点坐标: {}", destination);

        String responseBody = webClient.get()
                .uri(baiduMapConfig.getRouteUrl()+"/"+mode.getName(),uriBuilder -> uriBuilder

                        .queryParam("origin", origin)
                        .queryParam("destination",destination)
                        .queryParam("ak",baiduMapConfig.getAk())
                        .build()

                )
                .retrieve()
                .bodyToMono(String.class)
                .block(); // 这里使用 `block()` 让它同步执行

        log.info("路线API返回: {}", responseBody);

        JSONObject jsonObject = new JSONObject(responseBody);

        log.info(jsonObject.toString());


        return jsonObject;
    }
}
